package com.yangff.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yangff.entity.admin.entity.Admin;
import com.yangff.entity.admin.entity.dto.AdminDTO;
import com.yangff.entity.dto.AccountDTO;
import com.yangff.entity.vo.JwtVo;
import com.yangff.entity.vo.ResultVo;
import com.yangff.mapper.AdminMapper;
import com.yangff.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yangff.utils.JwtUtil;
import com.yangff.utils.MathUtil;
import com.yangff.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;

/**
 * <p>
 * 存储管理员的基本信息 服务实现类
 * </p>
 *
 * @author yangff
 * @since 2025-01-15
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    private final RabbitTemplate rabbitTemplate;

    @Override
    public Admin updateAdminByAccount(AdminDTO adminDTO) {
        Admin admin = getOne(new LambdaQueryWrapper<Admin>().eq(Admin::getAccount,adminDTO.getAccount()));

        if(adminDTO.getEmail() != null)admin.setEmail(adminDTO.getEmail());
        if(adminDTO.getPhoneNumber() != null) admin.setPhoneNumber(adminDTO.getPhoneNumber());
        if(adminDTO.getUsername() != null) admin.setUsername(adminDTO.getUsername());
        return admin;
    }

    @Override
    public JwtVo login(AccountDTO accountDTO) throws Exception {
        Admin one = getById(accountDTO.getAccount());

        JwtVo jwtVo = new JwtVo();
        try
        {
            if(MathUtil.checkSHA256(accountDTO.getPassword() , one.getPassword()) == true)
            {
                String token = JwtUtil.createJwtToken(accountDTO.getAccount(), "admin", JwtUtil.DEFAULT_TIME);

                jwtVo.setAccount(accountDTO.getAccount());
                jwtVo.setToken(token);
                jwtVo.setType("admin");

                rabbitTemplate.convertAndSend("fts.direct","save_admintoken",jwtVo);

            }
        }
        catch (Exception e)
        {
            //管理员没登录成功
        }


        return jwtVo;
    }
}
